package projects.android.sms.adapter;

import java.sql.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

import projects.android.sms.R;
import projects.android.sms.object.NumberHelper;
import projects.android.sms.object.UserRecord;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * Adapter managing the different conversations between the user and certain conversation partners.
 * 
 * @author Thomas Jaeger
 * @author Mario Kraml
 * @author Tassilo Posegga
 * @author Robert Schenkenfelder
 * 
 */
public class UserItemAdapter extends ArrayAdapter<UserRecord> {

	private final ArrayList<UserRecord> users;

	public UserItemAdapter(Context context, int textViewResourceId, ArrayList<UserRecord> users) {
		super(context, textViewResourceId, users);
		this.users = users;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View v = convertView;
		if (v == null) {
			LayoutInflater vi = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			v = vi.inflate(R.layout.listitem, null);
		}

		UserRecord user = users.get(position);

		TextView username = (TextView) v.findViewById(R.id.username);
		TextView message = (TextView) v.findViewById(R.id.message);
		TextView date = (TextView) v.findViewById(R.id.date);
		if (user != null) {
			ImageView avatar = (ImageView) v.findViewById(R.id.avatar);
			avatar.setBackgroundResource(R.drawable.ic_menu_archive);

			if (username != null) {
				username.setText(NumberHelper.resolveNumberToName(getContext(), user.getUsername()));
			}

			if (message != null) {
				int end = Math.min(40, user.getMessages().get(user.getMessages().size()-1).getMessage().length());
				message.setText(user.getMessages().get(user.getMessages().size()-1).getMessage().substring(0, end));
			}

			if (date != null) {
				Date d = user.getMessages().get(0).getDate();
				DateFormat sdf = SimpleDateFormat.getDateTimeInstance();
				date.setText(sdf.format(d));
			}
		}
		return v;
	}

	public ArrayList<UserRecord> getUsers() {
		return users;
	}
}
